#!/bin/sh -efux

srcdir="${srcdir=.}"
srcdir="$(realpath $srcdir)"
. "$srcdir/init.sh"

REPO="$1"; shift
[ -n "$REPO" ]
repo_expected="$srcdir/$REPO.repo"

useful_files="$srcdir/$REPO".repo.useful-files
[ -s "$useful_files" ] ||
	useful_files=

different_base=
fill_architecture=
check_args() {
	local architecture=
	local architectures=
	TEMP="$(getopt -o vhs -l help,basedir:,mapi,listonly,bz2only,compressedonly,hashonly,updateinfo:,bloat,no-scan,topdir:,sign,default-key:,progress,verbose,silent,oldhashfile,newhashfile,no-oldhashfile,no-newhashfile,partial,flat,create,origin:,label:,suite:,codename:,architectures:,description:,archive:,version:,architecture:,notautomatic:,cachedir:,useful-files:,changelog-since:,patch-basedir,prev-basedir:,add-list:,rm-list:,preferred-prev_compression: \
		-l bz2,no-bz2,xz,no-xz,zst,zstd,no-zst,no-zstd,maybe-unchanged \
		-l blake2b,no-blake2b -- "$@")"
	eval set -- "$TEMP"
	while :; do
		case "$1" in
			--architecture) shift; architecture=1 ;;
			--architectures) shift; architectures=1 ;;
			--basedir) shift; different_base="$1" ;;
			--) shift; break ;;
		esac
		shift
	done

	if [ -n "$architectures" ] && [ -z "$architecture" ]; then
		fill_architecture=1
	fi
	[ -z "$different_base" ] ||
		basedir="$different_base"
}

check_args "$@"

for a in $(set +f; echo "$repo_expected"/*); do
	arch="$(basename "$a")"
	case "$arch" in
		SRPMS.*) continue;;
	esac
	copy_pkgs "$arch"
	$GENBASEDIR "$@" \
		${different_base:+--basedir $different_base} \
		${fill_architecture:+--architecture="$arch"} \
		${useful_files:+--useful-files $useful_files} \
		--create \
		--topdir="$repo" \
		$arch
done

for a in $(set +f; echo "$repo_expected"/*); do
	arch="$(basename "$a")"
	case "$arch" in
		SRPMS.*) continue;;
	esac
	check_base "$arch"
done
